package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.StackProblem;

import java.util.LinkedList;

/**
 * https://leetcode.com/problems/basic-calculator/
 * +-()计算器
 * 玛德, 要是有长数字, 你就给个例子艹
 * <p>
 * leetcode 150 && 224 && 227 && 772
 *
 * @author tzp
 * @since 2020/11/18
 */
public class LC224 implements StackProblem {
    public int calculate(String s) {//(1+(4+5+2)-3 )+(6+ 8)
        LinkedList<Object> stack = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case ' ': {
                    break;
                }
                case '+': {
                    stack.offerLast(c);
                    break;
                }
                case '-': {
                    stack.offerLast(c);
                    break;
                }
                case '(': {//左括号和符号入栈
                    stack.offerLast(c);
                    break;
                }
                case ')': {//右括号不入栈
                    Object result = stack.removeLast();
                    Object left = stack.removeLast();
                    handleNumber(stack, (Integer) result);
                    break;
                }
                default: {//数字, 看情况
                    int num = 0;
                    int j;
                    for (j = i;
                         j < s.length() && s.charAt(j) >= '0' && s.charAt(j) <= '9';
                         j++) {
                        num = num * 10 + s.charAt(j) - '0';
                    }
                    i = j - 1;
                    handleNumber(stack, num);
                    break;
                }
            }
        }
        return (int) stack.getLast();
    }

    private void handleNumber(LinkedList<Object> stack, int num) {
        if (stack.size() == 0 || stack.getLast().equals('(')) {
            stack.offerLast(num);//入栈
        } else {
            Object operator = stack.removeLast();
            if (operator.equals('+')) {
                stack.offerLast((int) stack.removeLast() + num);
            } else if (operator.equals('-')) {
                stack.offerLast((int) stack.removeLast() - num);
            } else {
                throw new RuntimeException();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new LC224().calculate("1+22+3"));
        System.out.println(new LC224().calculate("1+22 -3"));
        System.out.println(new LC224().calculate("1+( 22-3)"));
        System.out.println(new LC224().calculate("1-(22-3)"));
        System.out.println(new LC224().calculate("1-22 -3"));
    }
}
